package com.appspot.newsographer.client;

import java.util.Date;
import java.util.HashMap;
import java.util.Set;
import com.gargoylesoftware.htmlunit.AlertHandler;
import com.gargoylesoftware.htmlunit.javascript.host.Window;
import java.util.ArrayList;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.SelectionHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.AbsolutePanel;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DecoratedTabPanel;
import com.google.gwt.user.client.ui.DockLayoutPanel;
import com.google.gwt.user.client.ui.DockPanel;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HasHorizontalAlignment.HorizontalAlignmentConstant;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.MultiWordSuggestOracle;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.SplitLayoutPanel;
import com.google.gwt.user.client.ui.SuggestBox;
import com.google.gwt.user.client.ui.TabLayoutPanel;
import com.google.gwt.user.client.ui.TabPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.MultiWordSuggestOracle.MultiWordSuggestion;
import com.google.gwt.user.datepicker.client.DateBox;
import com.google.gwt.user.client.rpc.*;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class GWTMaxi implements EntryPoint {
	
	private VerticalPanel mainPanel = new VerticalPanel();
	private AbsolutePanel totalPanel = new AbsolutePanel();
	private DockLayoutPanel navPanel = new DockLayoutPanel(Unit.EM);
	private HorizontalPanel topPanel = new HorizontalPanel();
	private Label totalLabel = new Label();
	private FlexTable flexEntryTable = new FlexTable();
	private Image image = new Image();
	private GuardianServiceAsync guardianService = (GuardianServiceAsync) GWT.create(GuardianService.class);
	private TextBox searchBox;
	private Button searchButton;
	private DateBox endDateBox;
	private DateBox startDateBox;
	private final CountryServiceAsync dataService = GWT.create(CountryService.class);
	private FlowPanel guardianNewsPanel;
	private TabPanel resultsTabPanel;
	private FlowPanel mapPanel;
	private FlowPanel tagCloudPanel;
	private SimplePanel tmpPanel;
	@Override
	public void onModuleLoad() {
		//callGuardianService("something");
		image.setUrl("http://us.123rf.com/400wm/400/400/kentoh/kentoh0910/kentoh091000170/5677295-natural-disasters-grunge-as-a-art-background.jpg");
		
		//setting up the search area
		HorizontalPanel searchAreaPanel = new HorizontalPanel();

		//search field
		searchBox = new TextBox();
		searchBox.setWidth("600px");
		//search button
		searchButton = new Button("Search");
		searchAreaPanel.add(searchBox);
		searchAreaPanel.add(new Label(" "));
		searchAreaPanel.add(searchButton);
		
		topPanel.setWidth("1000px");
		//topPanel.add(image);
		topPanel.add(searchAreaPanel);
		topPanel.setCellHorizontalAlignment(searchAreaPanel, HasHorizontalAlignment.ALIGN_CENTER);
		
		//set up a horizontal panel to hold the date picker.
		HorizontalPanel datePanel = new HorizontalPanel();
		
		//constructing start datePanel towards to left.
		AbsolutePanel leftNav = new AbsolutePanel();
		leftNav.add(new Label("Start Date"));
		startDateBox = new DateBox();
		startDateBox.setWidth("100px");
		startDateBox.setFormat(new DateBox.DefaultFormat(DateTimeFormat.getFormat("MM/dd/yyyy")));
		leftNav.add(startDateBox);
		
		//constructing end datePanel towards to right
		AbsolutePanel rightNav = new AbsolutePanel();
		rightNav.add(new Label("End Date"));
		endDateBox = new DateBox();
		endDateBox.setWidth("100px");
		endDateBox.setFormat(new DateBox.DefaultFormat(DateTimeFormat.getFormat("MM/dd/yyyy")));
		rightNav.add(endDateBox);
		
		//adding a gap between the fields and set alignment.
		Label toLabel = new Label("To");
		datePanel.add(leftNav);
		datePanel.setCellHorizontalAlignment(leftNav, HasHorizontalAlignment.ALIGN_LEFT);
		datePanel.add(toLabel);
		datePanel.setCellHorizontalAlignment(toLabel, HasHorizontalAlignment.ALIGN_CENTER);
		datePanel.add(rightNav);
		datePanel.setCellHorizontalAlignment(rightNav, HasHorizontalAlignment.ALIGN_RIGHT);
		
		//adding it to main panel
		mainPanel.add(topPanel);
		mainPanel.add(datePanel);
		mainPanel.setCellHorizontalAlignment(datePanel, HasHorizontalAlignment.ALIGN_CENTER);
		

	    //guardianNewsPanel.add(callGuardianService("earthquake"));
		//mainPanel.setCellHorizontalAlignment(resultsPanel, HasHorizontalAlignment.ALIGN_CENTER);
		//get specific div ids to each panel
		RootPanel.get("pageHeader").add(pageHeader());
		RootPanel.get("searchPanel").add(mainPanel);
		//RootPanel.get("layoutPanel").add(datePanel);
		
		class SearchButtonHandler implements ClickHandler {

			@Override
			public void onClick(ClickEvent event) {
				sendSearchStringToServer();
			}
			
			
			private void sendSearchStringToServer() {
				// Then, we send the input to the server.
				String DATE_FORMAT = "yyyy-MM-dd";
				DateTimeFormat dateFormat = DateTimeFormat.getFormat(DATE_FORMAT);
				Date startDate = startDateBox.getValue();
				Date endDate = endDateBox.getValue();
				String searchString = searchBox.getText();
				//2011-03-02
				String guardianStartDate = dateFormat.format(startDate);
				String guardianEndDate = dateFormat.format(endDate);
				callGuardianService(searchString, guardianStartDate, guardianEndDate);
				AsyncCallback<ArrayList<CountryData>> callBack = new AsyncCallback<ArrayList<CountryData>>() {
					public void onFailure(Throwable caught) {
					}

					@Override
					public void onSuccess(ArrayList<CountryData> result) {
						// TODO Auto-generated method stub
						//adding the results panel to main panel

					}
				};
				dataService.getCountryNames(searchString, callBack);
			}			
			
		}
		// Add a handler to send the name to the server
		SearchButtonHandler handler = new SearchButtonHandler();
		searchButton.addClickHandler(handler);
	}

	public FlowPanel populatePanel(HashMap<String, ArrayList<String>> result)
	{
		FlowPanel tmpPanel = new FlowPanel();
		Set<String> titles = result.keySet();
		String[] keys = new String[titles.size()];
		titles.toArray(keys);
		for(int i=0; i < keys.length; i++)
		{
			ArrayList<String> value = result.get(keys[i]);
			String test = null;
			//tmpPanel.add(new Label(keys[i]));
			//tmpPanel.add(new Anchor(value.get(0)));
			Anchor a = new Anchor(keys[i], true, value.get(0));
			a.getElement().setAttribute("style", "align:right");
			a.getElement().setAttribute("style", "font-size:150%");
			a.getElement().setAttribute("style", "display:block");
			tmpPanel.add(a);
			
			//tmpPanel.add(new Label("some text"));
		}
		return tmpPanel;
	}
	
	private void callGuardianService(String message, startDate, endDate)
	{	
		guardianService.searchGuardian(message, startDate, endDate, new AsyncCallback<HashMap<String, ArrayList<String>>>() {
			FlowPanel tempPanel = new FlowPanel();

			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub
			}

			public void onSuccess(HashMap<String, ArrayList<String>> result) {
				mainPanel.add(resultsPanel(result));
			}
		});
	}
	
	/**
	 * Construct the Tab panel to populate results.
	 * @return
	 */
	private TabPanel resultsPanel(HashMap<String, ArrayList<String>> result) {
		resultsTabPanel = new TabPanel();
		resultsTabPanel.setWidth("100%");
		resultsTabPanel.setHeight("100%");
		
		mapPanel = new FlowPanel();
		mapPanel.setHeight("550px");
		mapPanel.add(mapPanel(result));
		resultsTabPanel.add(mapPanel, "Map");
		
		tagCloudPanel = new FlowPanel();
		tagCloudPanel.setHeight("550px");
		resultsTabPanel.add(tagCloudPanel, "Tags");
		
		guardianNewsPanel = new FlowPanel();
		guardianNewsPanel.setHeight("550px");
		guardianNewsPanel.add(new Label("Guardian News goes here"));
		resultsTabPanel.add(guardianNewsPanel, "News");
		guardianNewsPanel.add(populatePanel(result));
		
		resultsTabPanel.addSelectionHandler(new SelectionHandler<Integer>(){
			public void onSelection(SelectionEvent<Integer> event) {
				if(event.getSelectedItem() == 2)
				{
					
				}
			}
		});
		resultsTabPanel.selectTab(0);
		
		return resultsTabPanel;
	}
	
	/**
	 * Draw the map and return it as vertical panel.
	 * @param result 
	 * @return
	 */
	private VerticalPanel mapPanel(HashMap<String, ArrayList<String>> result) {
		
	    GWTMaxiMap gwtMaxiMap = new GWTMaxiMap();
	    
	    VerticalPanel vp = new VerticalPanel();
	    vp.add(gwtMaxiMap);
	    vp.setWidth("100%");
	    vp.setCellHorizontalAlignment(gwtMaxiMap, HorizontalPanel.ALIGN_CENTER);		
	    gwtMaxiMap.draw(result);
	    return vp;
	}
	
	/**
	 * Construct the page header and return the an instance of {@link AbsolutePanel}
	 * @return
	 */
	private AbsolutePanel pageHeader() {
		final AbsolutePanel headerPanel = new AbsolutePanel();
		headerPanel.add(new Label("Please enter news topic genre to search | Ex: Reveloution, Natural Disaster etc"));
		return headerPanel;
	}

}